# -*- coding: utf-8 -*-
import netifaces
from gi.repository import GLib
import datetime
import re
import dbus
import dbus.mainloop.glib
import requests
from urllib.parse import quote
import subprocess
import os
import time
import string
import random
import json
import shutil
import http.client
img_path = os.path.join( os.getcwd(), 'image', 'capture.jpg')

def check_ModemManager_status():
    if not os.path.exists('/tmp/img'):
        os.makedirs('/tmp/img')
    try:
        # 使用subprocess运行mmcli命令并检查退出码
        subprocess.check_call(['mmcli', '-m', '0'])
        print("ModemManager工作正常")
    except subprocess.CalledProcessError:
        print("ModemManager出现错误，重启ModemManager服务...")
        subprocess.call(['systemctl', 'restart', 'ModemManager'])
    pass

def get_fileurl(file_path):
    file_name = os.path.basename(file_path)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60',
        'Referer': 'https://userscloud.com',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    }

    with open(file_path, 'rb') as file:
        file_content = file.read() 
    files = {
        'file': (file_name, file_content, 'image/jpeg')
    }
    # 其他表单数据
    data = {
        'sess_id': '',
        'utype': 'anon',
        'link_rcpt': '',
        'link_pass': '',
        'keepalive': '1',
    }
# 打印响应内容
    url = "https://userscloud.com"
    response = requests.get(url)

    # 检查是否成功获取页面
    if response.status_code == 200:
        # 使用正则表达式提取上传链接
        pattern = r'<form id="uploadfile" action="([^"]+)"'
        match = re.search(pattern, response.text)

        if match:
            upload_link = match.group(1)
            print("Upload Link:", upload_link)
            response = requests.post(upload_link, headers=headers, files=files, data=data)
            data = json.loads(response.text)
            # 提取文件code
            if data[0]['file_code']:
                file_code = data[0]['file_code']
                print("File Code:", file_code)
                # 访问结果页面
                result_url = f"https://userscloud.com/?op=upload_result&st=OK&fn={file_code}"
                result_response = requests.get(result_url)
                url_match = re.search(r'\[IMG\](.*?)\[/IMG\]', result_response.text)
                if url_match:
                    file_url = url_match.group(1)

                    # 移除 "_t"，如果存在的话
                    file_url = file_url.replace("_t.jpg", ".jpg")
                    return file_url
                else:
                    print("URL not found in the text.")
                    pass



    



def push_msg(title,content,token):
    url = 'https://www.pushplus.plus/send'
    payload = json.dumps({
        "token":token,
        "title":title,

        "content":content,
        "template":"html",
        "channel":"wechat"
    })
    headers = {
       'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
       'Content-Type': 'application/json'
    }
    requests.post(url, data=payload, headers=headers)
    print(content)
    pass
    

def get_ips(data):
    ips = []
    ipv4_pattern = r'^(10|172|192.168)\.'
    ipv6_pattern = r'^(fe80:|fc00:)'
    for iface in netifaces.interfaces():
        if iface != 'lo':
            iface_details = netifaces.ifaddresses(iface)
            
            if netifaces.AF_INET in iface_details:
                for ipv4 in iface_details[netifaces.AF_INET]:
                    if not ipv4['addr'].startswith('10.') and not ipv4['addr'].startswith('172.') and not ipv4['addr'].startswith('192.168'):
                        ips.append(ipv4['addr'])

            if netifaces.AF_INET6 in iface_details:
                for ipv6 in iface_details[netifaces.AF_INET6]:
                    if not re.match(ipv6_pattern, ipv6['addr']):
                        ips.append('['+ipv6['addr']+']')
        if iface.startswith('z'):
            if netifaces.AF_INET in iface_details:
                for ipv4 in iface_details[netifaces.AF_INET]:
                    ips.append(ipv4['addr'])
    ips = sorted(ips)
    urls = ['<a href="http://' + ip + ':8888">http://' + ip + ':8888</a>' for ip in ips] 
    if data['nps'] and data['npsport']:
        nps_addr = f'<a href=http://{data["nps"].split(":")[0]}:{data["npsport"]}>http://{data["nps"].split(":")[0]}:{data["npsport"]}</a>'
        urls.append(nps_addr)
    if data['sakurafrp_addr'] and data['sakurafrp_port']:
        sakura_addr = f'<a href=https://{data["sakurafrp_addr"]}:{data["sakurafrp_port"]}>http://{data["sakurafrp_addr"]}:{data["sakurafrp_port"]}</a>'
        urls.append(sakura_addr)

    return '</br>'.join(urls)

    
def get_image():
    os.system('timeout 1s mjpg_streamer -i "input_uvc.so -d /dev/video2 -r 1920x1080 -f 5" -o "output_file.so -f /tmp/img"')
    full_paths = [os.path.join('/tmp/img', f) for f in os.listdir('/tmp/img')]
    latest_img = max(full_paths, key=os.path.getmtime)
    return latest_img

def msg_added_handler(path, received):
    if not received:
        return
    msg = bus.get_object("org.freedesktop.ModemManager1",path)
    props_iface = dbus.Interface(msg, "org.freedesktop.DBus.Properties")
    content = props_iface.GetAll("org.freedesktop.ModemManager1.Sms")
    while not content['Text'].strip():
        content = props_iface.GetAll("org.freedesktop.ModemManager1.Sms")
    text = "Number: "+content['Number']+"\nText:\n"+content['Text']+"\nTime: "+content['Timestamp']
    if content['Text']:
        msg =  content['Text'].strip()
        config_path = os.path.join( os.getcwd(), "config.json")
        with open(config_path, 'r') as f:
            json_data = f.read()
        config_data = json.loads(json_data)
        admin_value = config_data["admin"]
        push_token = config_data["plusapi"]

        action_dic = {'开机':2,'关机':3,'强制关机':4,'poweron':2,'poweroff':3,'forceoff':4,'on':2,'off':3}
        if msg.split(' ',2)[0] == admin_value:
            if  msg.split(' ',2)[1] in action_dic:
                content['Text'] = msg.split(' ',2)[1]
                ser = serial.Serial('ttyUSB0', 115200 ) 
                data = bytes([247, action_dic[msg.split(' ',2)[1]], 251])
                ser.write(data)
                ser.close()
            elif msg.split(' ',2)[1] =='截图':
                latest_img = get_image()
                fileurl = get_fileurl(latest_img)
                shutil.rmtree("/tmp/img") 
                os.mkdir("/tmp/img")
                content['Text'] = "<img src='"+fileurl+"'>"
            elif msg.split(' ',2)[1] in ['地址','ip','IP']:
                content['Text'] = get_ips(config_data)
            elif msg.split(' ',2)[1] =='shell':
                command = msg.split(' ',2)[2]
                shell_command = f"({command}) &"  
                subprocess.Popen(shell_command, shell=True)
                content['Text'] ='执行shell命令'
            elif msg.split(' ',2)[1] in ['重置','reset','RESET']:
                os.remove(config_path)
                subprocess.Popen("sleep 30 && reboot", shell=True)
                content['Text'] ='重置系统'

    old_time = datetime.datetime.fromisoformat(content['Timestamp'])
    content['Timestamp'] = old_time.strftime('%Y-%m-%d %H:%M:%S')
    content['Number'] = re.sub(r'^(\+|00)?86', '', content['Number'])    

    push_msg(content['Number'],content['Text'],push_token)
    pass
    

if __name__ == '__main__':
    check_ModemManager_status()
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus()
    try:
        object = bus.get_object("org.freedesktop.ModemManager1","/org/freedesktop/ModemManager1/Modem/0")
        object.connect_to_signal("Added", msg_added_handler, dbus_interface="org.freedesktop.ModemManager1.Modem.Messaging")
    except dbus.DBusException:
        traceback.print_exc()
        print(usage)
        sys.exit(1)
    loop = GLib.MainLoop()
    loop.run()
